package com.xgkj.diyiketang.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CheckUpdateTask;
import com.xgkj.diyiketang.util.APKInstallUtils;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.DownloadRunnable;
import com.xgkj.diyiketang.util.ToastUtil;

public class AboutActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private TextView mVersionText;
    private RelativeLayout mCheckUpdateLayout;
    private ProgressDialog mProgressDlg;
    private String downUrl;
    private String appVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about);
        mContext = this;
        initView();
    }

    private void initView() {
        mVersionText = (TextView) findViewById(R.id.app_version);
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        appVersion = info.versionName;
        mVersionText.setText(String.format(getString(R.string.version_code), appVersion));
        mCheckUpdateLayout = (RelativeLayout) findViewById(R.id.checkupdate_layout);
        mCheckUpdateLayout.setOnClickListener(this);
        ((TextView) findViewById(R.id.back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        checkUpdate();
    }

    private void checkUpdate() {
        CheckUpdateTask task = new CheckUpdateTask();
        task.addListener(listener);
        getEatShowApp().getTaskManager().addTask(task);
    }

    private TaskEventListener listener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (data != null) {
                JSONObject json = (JSONObject) data;
                String new_version = json.getString("latestVersion");
                downUrl = json.getString("downloadUrl");
                if (!new_version.equals(appVersion)) {
                    showDialog();
                } else {
                    ToastUtil.showMessage(mContext, R.string.app_no_update);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    private void showDialog() {
        DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.client_has_update), getString(R.string.ok), getString(R.string.cancle), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
//                DownloadRunnable runable = new DownloadRunnable(downUrl, mContext, handler);
//                Thread thread = new Thread(runable);
//                thread.start();
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, null);
//		http://gdown.baidu.com/data/wisegame/fdb272a1a62f50ea/58tongcheng_6080.apk
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DownloadRunnable.DOWNLOAD_ALREADY_EXIST:
                case DownloadRunnable.DOWNLOAD_SUCCEED:
                    if (mProgressDlg != null) {
                        mProgressDlg.dismiss();
                        mProgressDlg = null;
                    }
                    APKInstallUtils.installApk(mContext, msg.obj.toString());
                    break;
                case DownloadRunnable.DOWNLOAD_PROGRESS:
                    updateProDialogMsg(msg.arg1);
                    break;
                case DownloadRunnable.DOWNLOAD_FAIL:
                    if (mProgressDlg != null) {
                        mProgressDlg.dismiss();
                        mProgressDlg = null;
                    }
                    Toast.makeText(mContext, R.string.no_network, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };

    private void updateProDialogMsg(int progress) {
        if (mProgressDlg != null && mProgressDlg.isShowing()) {
            mProgressDlg.setMessage(getString(R.string.updateclient, progress));
            mProgressDlg.setProgress(progress);
            if (progress == 100) {
                mProgressDlg.dismiss();
            }
        } else {
            createProgressDialog(progress);
        }
    }

    private void createProgressDialog(int percent) {
        mProgressDlg = new ProgressDialog(mContext);
        mProgressDlg.setTitle(R.string.prompt);
        mProgressDlg.setMessage(getString(R.string.updateclient, percent));
        mProgressDlg.setCanceledOnTouchOutside(false);
        mProgressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDlg.setCancelable(false);
        mProgressDlg.setProgress(percent);
        mProgressDlg.setProgressNumberFormat(null);
        mProgressDlg.setProgressPercentFormat(null);
        mProgressDlg.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
